package com.wxsong.authplatform.authweb.controller.login;

import com.wxsong.authplatform.authweb.controller.common.Const;
import com.wxsong.authplatform.authweb.model.users.Users;
import com.wxsong.authplatform.authweb.service.users.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;

@Controller
@RequestMapping("/login")
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private UserService userService;

    @RequestMapping(value = "/to_login")
    public String loginPage(){
        return "main/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(ModelMap modelMap, String userName, String password){

        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            String name = subject.getPrincipal().toString();
            modelMap.put("name", name);
            Users users = userService.getByUserName(userName);
            subject.getSession().setAttribute(Const.SESSION_USER_KEY, users);
            logger.info("登录成功， 用户名："+userName);
            return "redirect:/main/index";
        }catch (AuthenticationException e){
            logger.error("登录失败， 用户名："+userName + "，登录密码：" + password);
        }
        modelMap.put("info", "登录失败");
        return "forward:/login/to_login";
    }

    /**
     * 登出
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(ModelMap modelMap, String userName){
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
            logger.info("登录成功， 用户名："+userName);
            return "redirect:/main/index";
        }catch (AuthenticationException e){
            logger.error("登录失败， 用户名："+userName );
        }
        modelMap.put("info", "登录失败");
        return "forward:/login/to_login";
    }
}
